<?php

namespace App\Think\SdkPayment;

/**
 * 七月支付 SDK
 */
class Qiyue{

	// http://july.tjtaige.cn/index.php/lb/index
	// 账号：qiyue003
	// 密码：qiyue003
	// 商户密钥：22e6e19a5dbd9248

	public function __construct(){
		$this->api_url = 'http://july.tjtaige.cn/index.php/home/payali/GetOrderLink';
		//商户号
		$this->acc = 'qiyue003';
		//商户密钥
		$this->key = '22e6e19a5dbd9248';
	}


	/**
	 * 创建支付url
	 */
	public function pay_url($args){
		log_to($args, "paySDKpay-payurl-".__CLASS__);
		
		//生成签名
		$token  = $this->generateAppKey($this->acc, $this->key, $args['amount']);
		$webOid = isset($args['out_trade_no']) ? $args['out_trade_no'] : date("YmdHis").mt_rand(1000,9999);
		$post_data = [
			'money'   => $args['amount'],
			'webName' => $this->acc,
			'webOid'  => $webOid,
			'token'   => $token,
		];
		
		$ret  = json_decode($this->request_post($this->api_url, $post_data),true);
		log_to(['param'=>$args,'ret'=>$ret], "paySDKpay-".__CLASS__);
		if($ret['code'] == 0){
			$rs['code'] = 1;
			$rs['out_trade_no'] = $webOid;
			$rs['pay_url']      = $ret['data'];
		}else{
			$rs['code'] = -$ret['code'];
			$rs['msg']  = $ret['msg'];
		}
		return $rs;	
	}

	/**
	 * 支付回调
	 */
	public function response(){
		log_to($_REQUEST, "paySDKpay-response-".__CLASS__);
		$res = $_REQUEST;
		$rs  = [];
		$rs['status']     = ($res['payStatus'] == '1') ? 1 : 2;
		$rs['order_sn']   = $res['oId'];
		$rs['money_real'] = $res['payNum'];
		$rs['fee'] 		  = $res['fee'];
		return $rs;
	}



	private function request_post($url = '', $post_data = array()){
        if (empty($url) || empty($post_data)) {
            return false;
        }
        $o = "";
        foreach ( $post_data as $k => $v ) 
        { 
            $o.= "$k=" . urlencode( $v ). "&" ;
        }
        $post_data = substr($o,0,-1);
        $postUrl = $url;
        $curlPost = $post_data;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        return $data;
    }

	public function generateAppKey($acc,$key, $content)
	{
	    $time = date("YmdHi");
	    $fMd5  = md5($acc.$content.$time);
	    $token = md5($fMd5.$key);
	    return $token;
	}

    

}